import { engine } from "../engine/engine";

function isNull(obj: any) {
    return obj == null || obj == undefined;
}
/**
 * cgw20220527
 * 对本地存档的封装
 */
export default class LocalValue {


    protected value: any;
    protected name: string = ''
    protected def: any;
    protected dataFlag: boolean = false;

    constructor(name: string, def: any) {
        this.name = name;
        this.setDefault(def)
        this.load();
    }

    load() {
        this.dataFlag = this.loadValue()
    }

    setDefault(def: any) {
        this.def = def;
    }

    protected loadValue(): boolean {
        let save = engine.localStorage.getItem(this.name);
        if (!isNull(save)) {
            this.value = save;
            return true;
        } else {
            this.value = this.def;
            return false;
        }

    }

    hasData() {
        return this.dataFlag;
    }

    getValue() {
        return this.value
    }

    setValue(v: any, isSave: boolean = true) {
        this.value = v;
        if (isSave) {
            this.save();
        }
    }

    save() {
        engine.localStorage.setItem(this.name, this.value)
    }

    getInt() {
        return parseInt("" + this.value)
    }

    updateValue(n: number, param?: any) {
        this.setValue(this.getInt() + n)
    }
}